package com.ithiema.reggie.Service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ithiema.reggie.Mapper.OrderMapper;
import com.ithiema.reggie.Service.*;
import com.ithiema.reggie.common.BaseContext;
import com.ithiema.reggie.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;


    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;


    //提交订单 用户下单
    @Override
    public void submit(Orders orders) {
        //1. 准备数据
        //获取当前登陆用户
        long currentId = BaseContext.getCurrentId();
        //获取地址簿的信息
        AddressBook byId = addressBookService.getById(orders.getAddressBookId());
        //获取用户信息  要获取当前操作的id
        User user  = userService.getById(currentId);
        //User byId1 = userService.getById(orders.getId());   一会试试表里的id


        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> lwp = new LambdaQueryWrapper<>();
        lwp.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(lwp);
        //订单号
        long orderId  = IdWorker.getId();
        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        List<OrderDetail> orderDetails = list.stream().map((shoppingCartItem) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(shoppingCartItem.getNumber()); //数量
            orderDetail.setDishFlavor(shoppingCartItem.getDishFlavor()); //口味
            orderDetail.setDishId(shoppingCartItem.getDishId()); //菜品id
            orderDetail.setSetmealId(shoppingCartItem.getSetmealId());//套餐id
            orderDetail.setName(shoppingCartItem.getName()); //名称
            orderDetail.setImage(shoppingCartItem.getImage()); //图片
            orderDetail.setAmount(shoppingCartItem.getAmount());//金额（单价）
            amount.addAndGet(shoppingCartItem.getAmount().multiply(new BigDecimal(shoppingCartItem.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(currentId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());  //登陆用户名
        orders.setConsignee(byId.getConsignee());//收货人
        orders.setPhone(byId.getPhone());
        orders.setAddress((byId.getProvinceName() == null ? "" : byId.getProvinceName())
                + (byId.getCityName() == null ? "" : byId.getCityName())
                + (byId.getDistrictName() == null ? "" : byId.getDistrictName())
                + (byId.getDetail() == null ? "" : byId.getDetail()));


        //2. 保存到订单表
         this.save(orders);
        //3 保存到订单明细表
        orderDetailService.saveBatch(orderDetails);
        //4. 清空购物车
        shoppingCartService.remove(lwp);

    }
}